package com.example.administrator.social.activitys;

import android.app.DownloadManager;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.example.administrator.social.R;
import com.example.administrator.social.util.AllenUtils;
import com.example.administrator.social.util.HttpUtils;
import com.example.administrator.social.util.request.CustomRequest;
import com.example.administrator.social.view.CircleImageView;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener,TextWatcher,TextView.OnEditorActionListener {
    Context mContext;
    EditText mNickNameText,mUserNameText,mPasswordText,mPhoneText,mVerificationCodeText;
    TextView mEmptyText;
    Button mVerificationCodeButton,mRegisterButton;
    ImageView mGoBackImage;
    CircleImageView mHeaderImage;
    Toolbar mToolbar;

    EditText[] textViews = new EditText[]{mNickNameText,mUserNameText,mPasswordText,mPhoneText,mVerificationCodeText};
    RequestQueue mRequestQueue;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        mContext = this;
        AllenUtils.setActionBarColor(getWindow(),this,R.color.toolbar_color);
        mToolbar = (Toolbar) findViewById(R.id.register_toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        mRequestQueue = Volley.newRequestQueue(mContext);
        initView();
    }

    private void initView() {
        mGoBackImage = (ImageView) findViewById(R.id.register_user_go_back);
        mHeaderImage = (CircleImageView) findViewById(R.id.register_header_image);
        mEmptyText = (TextView) findViewById(R.id.register_user_empty);
        mRegisterButton = (Button) findViewById(R.id.register_button);
        mVerificationCodeButton = (Button) findViewById(R.id.register_get_verification_code_button);
        mVerificationCodeText = (EditText) findViewById(R.id.register_edit_verification_code);
        mNickNameText = (EditText) findViewById(R.id.register_nick_name_edit);
        mUserNameText = (EditText) findViewById(R.id.register_user_name_edit);
        mPasswordText = (EditText) findViewById(R.id.register_user_pwd_edit);
        mPhoneText = (EditText) findViewById(R.id.register_user_phone_edit);

        mNickNameText.setOnEditorActionListener(this);
        mUserNameText.setOnEditorActionListener(this);
        mPasswordText.setOnEditorActionListener(this);
        mPhoneText.setOnEditorActionListener(this);
        mVerificationCodeText.setOnEditorActionListener(this);

        mRegisterButton.setOnClickListener(this);
        mGoBackImage.setOnClickListener(this);
        mEmptyText.setOnClickListener(this);
        mVerificationCodeButton.setOnClickListener(this);
        mHeaderImage.setOnClickListener(this);

        mNickNameText.addTextChangedListener(this);
        mUserNameText.addTextChangedListener(this);
        mPasswordText.addTextChangedListener(this);
        mPhoneText.addTextChangedListener(this);

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.register_user_empty:
                emptyText();
                break;
            case R.id.register_user_go_back:
                finish();
                break;
            case R.id.register_button:
                if(isAllowToRegister&&checkedText()){
                    doHttpRegisterUser();
                }
                break;
            case R.id.register_get_verification_code_button:
                getIdentifyingCode();
                break;
            case R.id.register_header_image:
                setHeaderImage();
                break;
        }
    }

    /**
     * 设置头像
     */
    private void setHeaderImage() {
    }


    /** 清空所有文本*/
    private void emptyText() {
        mNickNameText.setText("");
        mUserNameText.setText("");
        mPasswordText.setText("");
        mPhoneText.setText("");
        mVerificationCodeText.setText("");
    }

    /**
     * 获取手机验证码
     */
    public void getIdentifyingCode() {
    }


    /**
     * 发送请求注册用户
     */
    private void doHttpRegisterUser() {
       String url = HttpUtils.HTTP_URL+"regUser";
       CustomRequest request = new CustomRequest(url, Request.Method.POST, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                System.out.println(" doHttpRegisterUser response = " + response);
                finish();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                System.out.println("doHttpRegisterUser volleyError = " + volleyError);
            }
        });

       Map<String,String> map = new HashMap<>();
       map.put("name",mUserNameText.getText().toString());
       map.put("nick_name",mNickNameText.getText().toString());
       map.put("password",mPasswordText.getText().toString());
       map.put("phone",mPhoneText.getText().toString());
       request.setParamsMap(map);
       mRequestQueue.add(request);
    }

    boolean isAllowToRegister = true;
    private boolean checkedText() {
        boolean isOk = true;
        if(!AllenUtils.isNickNameOk(mNickNameText.getText().toString())){
            //editInputError(mPhoneText,"长度1到20!");
           // Toast.makeText(mContext,"昵称长度1-20",Toast.LENGTH_SHORT).show();
            editInputError(mNickNameText,"昵称长度1-20");
            isOk =  false;
        }

        if(!AllenUtils.isUserName(mUserNameText.getText().toString())){
            // editInputError(mUserNameText,"字母开头，允许5-16字节，允许字母数字下划线");
          //  Toast.makeText(mContext,"用户名由字母、数字组成，5-16",Toast.LENGTH_SHORT).show();
            editInputError(mUserNameText,"字母、数字组成，长度5-16");
            isOk =  false;
        }
        if(!AllenUtils.isPasswordOk(mPasswordText.getText().toString())){
            // editInputError(mPasswordText,"以字母开头，长度在6~18之间!");
           // Toast.makeText(mContext,"密码由字母、数字、下划线组成，6-18",Toast.LENGTH_SHORT).show();
            editInputError(mPasswordText,"由字母、数字、下划线组成，6-18");
            isOk =  false;
        }

        //验证名称是否合格
        if(!AllenUtils.isMobile(mPhoneText.getText().toString())){
           // editInputError(mPhoneText,"手机号码格式错误!");
          //  Toast.makeText(mContext,R.string.phone_error,Toast.LENGTH_SHORT).show();
            editInputError(mPhoneText,"请输入正确的手机号码！");
            isOk =  false;
        }
        return isOk;
    }

    /**
     * 文本输入错误提醒
     * @param view  控件
     * @param value 提醒内容
     */
    public  void editInputError(EditText view,String value){
        Drawable drawable = getResources().getDrawable(R.drawable.edit_input_error);
        drawable.setBounds(0,0,40,0);
        view.setError(value, drawable);
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        isAllowToRegister = checkedText();
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        switch (v.getId()){
            case R.id.register_nick_name_edit:
            case R.id.register_user_name_edit:
            case R.id.register_user_pwd_edit:
            case R.id.register_user_phone_edit:
            case R.id.register_edit_verification_code:
                for(int i=0;i<textViews.length;i++){
                    if (v==textViews[i]&&i+1<textViews.length-1){
                        textViews[i].clearFocus();
                        textViews[i+1].requestFocus();
                        return true;
                    }
                    if(i+1>=textViews.length-1){
                        mRegisterButton.requestFocus();
                        return true;
                    }
                }
                return true;
        }
        return false;
    }







}
